<script setup>
import UploadPhoto from "@/components/Upload/uploadPhoto.vue";
import {ElMessage} from "element-plus";
import {getToken} from "@/api/qiniu.js";
import * as qiniu from "qiniu-js";
import {userOrderState} from "@/store/index.js";
import {updateOrder} from "@/api/wxz/order.js";
import tab from "@/plugins/tab.js";

const loading = ref(false);
const router = useRouter();
const orderState = userOrderState();

const lists = [ref([]), ref([]), ref([]), ref([])];
const refs = [ref(), ref(), ref(), ref()];

const handleGetList = (index, list) => lists[index].value = list;
const handleClearAll = () => {
  refs.forEach(r => r.value?.clear());
  lists.forEach(l => l.value = []);
};

const uploadToQiniu = async () => {
  loading.value = true;
  if (lists.some(list => list.value.length === 0)) {
    ElMessage.warning('请先选择文件');
    loading.value = false;
    return;
  }
  try {
    const qiNiuInfo = (await getToken()).data;
    for (let i = 0; i < lists.length; i++) {
      await uploadList(lists[i].value, i + 1, qiNiuInfo);
    }
    orderState.upload.isUploads = 1;
    await updateOrder(orderState.upload);
    location.href = '/index';
  } catch (e) {
    console.error('获取上传凭证失败', e);
    ElMessage.error('获取上传凭证失败');
  }
  loading.value = false;
};

const uploadList = async (list, name, info) => {
  const uploadPromises = list.map((file, index) => {
    return new Promise((resolve, reject) => {
      const ext = file.name.substring(file.name.lastIndexOf('.'));
      const key = `uploads-photo/${orderState.upload.id}/${name}-${index + 1}${ext}`;
      const putExtra = {fname: file.name, mimeType: ["image/png", "image/jpeg", "image/jpg"]};
      const config = {useCdnDomain: true, region: qiniu.region.z2};
      const options = {quality: 0.6, noCompressIfLarger: true, maxWidth: 1600, maxHeight: 900};

      qiniu.compressImage(file.raw, options).then(data => {
        qiniu.upload(data.dist, key, info.token, putExtra, config).subscribe({
          next: () => {
          },
          error: (err) => {
            console.error('上传失败', err);
            ElMessage.error(`文件 ${file.name} 上传失败`);
            reject(err);
          },
          complete: (res) => {
            file.url = `${info.domain}/${res.key}`;
            ElMessage.success(`文件 ${file.name} 上传成功`);
            resolve();
          }
        });
      }).catch(err => {
        console.error('图片压缩失败', err);
        ElMessage.error(`文件 ${file.name} 压缩失败`);
        reject(err);
      });
    });
  });
  await Promise.all(uploadPromises);
};

const onBack = () => {
  tab.closeOpenPage({path: "/index"})
}
</script>

<template>
  <div class="upload-wrapper" v-loading="loading">
    <!-- 固定顶部返回栏 -->
    <el-page-header
        class="top-header"
        @back="onBack"
        content="上传订单图片"
    />
    <transition-group name="fade-up" tag="div">
      <el-card
          v-for="(title, i) in [
          '1.机主签名截图（1张）',
          '2.修单前确认电脑状态（至多6张）',
          '3.维修过程中（至多6张）',
          '4.维修完成后（至多6张）'
        ]"
          :key="i"
          class="upload-card"
      >
        <h4 style="margin: 10px 0 10px">{{ title }}</h4>
        <p v-if="i === 1" style="color: #5a5e66;margin: 0 0 15px">
          *1.合页朝下竖起来看b面和c面的松紧程度(拍出松的缝隙)<br />
          *2.触摸板下摁，两边(拍出凹陷程度)<br />
          *3.检查全机有无缝隙<br />
          *4.屏幕是否开机后无破损，显卡是否正常存在
        </p>
        <p v-if="i === 2" style="color: #5a5e66;margin: 0 0 15px">
          *1.拆机拍下主板等<br />
          *2.安装软件的记录
        </p>
        <p v-if="i === 3" style="color: #5a5e66;margin: 0 0 15px">
          *1.电脑bc面<br />
          *2.触摸板<br />
          *3.缝隙<br />
          *4.电脑屏幕<br />
          拍一遍
        </p>
        <upload-photo :ref="refs[i]" :limit="i === 0 ? 1 : 6" @list="l => handleGetList(i, l)"/>
      </el-card>
    </transition-group>

    <div class="btn-group">
      <el-button @click="onBack">返回</el-button>
      <el-button @click="handleClearAll">清空</el-button>
      <el-button class="animated-btn" type="primary" @click="uploadToQiniu">提交订单</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.upload-wrapper {
  width: 85%;
  margin: 20px auto;
  background: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
  padding: 20px;
  border-radius: 10px;
}

.top-header {
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.upload-card {
  margin-bottom: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  }
}

.fade-up-enter-active, .fade-up-leave-active {
  transition: all 0.4s ease;
}

.fade-up-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.fade-up-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.btn-group {
  text-align: center;
  margin-top: 20px;
}

.animated-btn {
  background: linear-gradient(270deg, #42a5f5, #478ed1, #42a5f5);
  background-size: 400% 400%;
  animation: gradientMove 6s ease infinite;
  border: none;

  &:hover {
    transform: scale(1.05);
  }
}

.btn-group {
  text-align: center;
  margin-top: 20px;

  .el-button {
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
    }
  }
}


@keyframes gradientMove {
  0% {
    background-position: 0 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0 50%;
  }
}
</style>
